<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="老人姓名" prop="elderName">
        <el-input
          v-model="queryParams.elderName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="床位名称" prop="bedName">
        <el-input
          v-model="queryParams.bedName"
          placeholder="请输入床位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="入住状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="checkInList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="老人账号" align="center" prop="elderName" />
      <el-table-column label="当月入住费用" align="center" prop="monthlyFee" />
      <el-table-column label="床位名称" align="center" prop="bedName" />
      <el-table-column
        label="入住时间"
        align="center"
        prop="checkInTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkInTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="预计退房时间"
        align="center"
        prop="expectedCheckOutTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedCheckOutTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.check_in_audit"
            :value="scope.row.auditStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.status === '0' && scope.row.auditStatus === '0'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            >审核</el-button
          >
          <el-button
            v-if="scope.row.status === '0' && scope.row.auditStatus === '1'"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="handleCheckOut(scope.row)"
            >退住</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入住管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人" prop="elderUserId">
          <el-select
            v-model="form.elderUserId"
            placeholder="请选择老人"
            @change="handleElderChange"
          >
            <el-option
              v-for="item in elderOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="老人自理能力" prop="elderSelfCare">
          <el-select
            v-model="form.elderSelfCare"
            placeholder="请选择老人自理能力"
            @change="handleElderSelfCareChange"
          >
            <el-option
              v-for="item in dict.type.elder_self_care"
              :key="item.value"
              :label="item.label + '(' + item.raw.remark + ')'"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="床位" prop="bedId">
          <el-select
            v-model="form.bedId"
            placeholder="请选择床位"
            @change="handleRoomChange"
          >
            <el-option
              v-for="item in bedOptions"
              :key="item.id"
              :label="item.bedName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间" prop="checkInTime">
          <el-date-picker
            v-model="form.checkInTime"
            type="datetime"
            placeholder="选择入住时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="预计退房" prop="expectedCheckOutTime">
          <el-date-picker
            v-model="form.expectedCheckOutTime"
            type="datetime"
            placeholder="选择预计退房时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核入住申请对话框 -->
    <el-dialog
      :title="'审核入住申请'"
      :visible.sync="auditOpen"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="auditForm"
        :model="auditForm"
        :rules="auditRules"
        label-width="80px"
      >
        <el-form-item label="老人姓名">
          <span>{{ auditForm.elderName }}</span>
        </el-form-item>
        <el-form-item label="当前余额">
          <span>{{ auditForm.balance }} 元</span>
        </el-form-item>
        <el-form-item
          label="入住费用"
          prop="monthlyFee"
          v-if="auditForm.auditStatus === '1'"
        >
          <el-input-number
            v-model="auditForm.monthlyFee"
            :min="0"
            :precision="2"
            :step="100"
            controls-position="right"
            style="width: 200px"
          >
          </el-input-number>
          <span style="margin-left: 10px">元/月</span>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            placeholder="请输入审核备注"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuditForm">确 定</el-button>
        <el-button @click="cancelAudit">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCheckIn,
  getCheckIn,
  delCheckIn,
  addCheckIn,
  updateCheckIn,
  exportCheckIn,
  auditCheckIn,
  checkOut,
} from "@/api/system/checkIn";
import { listUser, listElder } from "@/api/system/user";
import { listBed } from "@/api/system/bed";
export default {
  name: "CheckIn",
  dicts: ["sys_normal_disable", "check_in_audit", "elder_self_care"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入住管理表格数据
      checkInList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        elderName: null,
        bedName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        elderUserId: [
          { required: true, message: "老人不能为空", trigger: "change" },
        ],
        bedId: [{ required: true, message: "房间不能为空", trigger: "change" }],
        checkInTime: [
          { required: true, message: "入住时间不能为空", trigger: "blur" },
        ],
        elderSelfCare: [
          {
            required: true,
            message: "老人自理能力不能为空",
            trigger: "change",
          },
        ],
        expectedCheckOutTime: [
          { required: true, message: "预计退房时间不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value && new Date(value) < new Date(this.form.checkInTime)) {
                callback(new Error("预计退房时间不能小于入住时间"));
              }
              callback();
            },
          },
        ],
      },
      // 老人选项
      elderOptions: [],
      // 房间选项
      bedOptions: [],
      // 审核对话框
      auditOpen: false,
      auditForm: {
        id: null,
        auditStatus: "1",
        auditRemark: null,
        monthlyFee: 2000,
      },
      auditRules: {
        auditStatus: [
          { required: true, message: "审核状态不能为空", trigger: "change" },
        ],
        monthlyFee: [
          { required: true, message: "入住费用不能为空", trigger: "blur" },
          { type: "number", message: "入住费用必须为数字", trigger: "blur" },
        ],
      },
      // 老人信息
      elderInfo: {
        elderName: "",
        balance: 0,
      },
      // 老人自理能力
      elderSelfCareOptions: [],
    };
  },
  mounted() {
    this.getList();
    this.getElderOptions();
    this.getRoomOptions();
  },
  activated() {
    this.getList();
    this.getElderOptions();
    this.getRoomOptions();
  },
  methods: {
    // 老人自理能力选择框变化
    handleElderSelfCareChange(value) {
      const select = this.dict.type.elder_self_care.find(
        (item) => item.value === value
      );
      this.form.monthlyFee = select.raw.remark;
    },
    /** 查询入住管理列表 */
    getList() {
      this.loading = true;
      return listCheckIn(this.queryParams).then((response) => {
        this.checkInList = response.rows;
        this.total = response.total;
        this.loading = false;
        return response;
      });
    },
    /** 获取老人选项 */
    getElderOptions() {
      listElder().then((response) => {
        this.elderOptions = response.rows;
      });
    },
    /** 获取房间选项 */
    getRoomOptions() {
      listBed({
        pageNum: 1,
        pageSize: 9999,
      }).then((response) => {
        this.bedOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        elderUserId: null,
        elderName: null,
        bedId: null,
        bedName: null,
        checkInTime: null,
        expectedCheckOutTime: null,
        actualCheckOutTime: null,
        status: "0",
        remark: null,
        elderSelfCare: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getElderOptions();
      this.getRoomOptions();
      this.reset();
      this.open = true;
      this.title = "添加入住管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCheckIn(id).then((response) => {
        this.form = response.data;
        // 重新获取老人选项，包含当前选中的老人
        listUser().then((userResponse) => {
          const allElders = userResponse.rows.filter((item) =>
            item.roles.some((role) => role.roleKey === "elder")
          );
          // 使用已有的入住列表数据，但排除当前正在编辑的记录
          const checkedInElderIds = this.checkInList
            .filter((item) => item.status === "0" && item.id !== id)
            .map((item) => item.elderUserId);
          // 过滤掉已入住的老人，但保留当前选中的老人
          this.elderOptions = allElders.filter(
            (elder) => !checkedInElderIds.includes(elder.userId)
          );
        });
        this.open = true;
        this.title = "修改入住管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCheckIn(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCheckIn(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除入住管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCheckIn([ids]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/checkIn/export",
        {
          ...this.queryParams,
        },
        `checkIn_${new Date().getTime()}.xlsx`
      );
    },
    /** 老人选择框变化 */
    handleElderChange(value) {
      const elder = this.elderOptions.find((item) => item.userId === value);
      if (elder) {
        this.form.elderName = elder.userName;
      }
    },
    /** 房间选择框变化 */
    handleRoomChange(value) {
      const bed = this.bedOptions.find((item) => item.id === value);
      if (bed) {
        this.form.bedName = bed.bedName;
      }
    },
    /** 审核按钮操作 */
    handleAudit(row) {
      this.resetAudit();
      const id = row.id || this.ids;
      this.auditForm.id = id;

      // 获取入住记录详情
      getCheckIn(id).then((response) => {
        this.auditForm = response.data;
        this.auditOpen = true;
        this.auditForm.auditStatus = "1";
      });
    },
    // 审核表单重置
    resetAudit() {
      this.auditForm = {
        id: null,
        auditStatus: "1",
        auditRemark: null,
        monthlyFee: 0,
      };
      this.resetForm("auditForm");
    },
    /** 提交审核 */
    submitAuditForm() {
      this.$refs["auditForm"].validate((valid) => {
        if (valid) {
          if (this.auditForm.auditStatus === "2") {
            this.auditForm.monthlyFee = 0;
          }

          // 确保monthlyFee是数字类型
          const monthlyFee = parseFloat(this.auditForm.monthlyFee);

          const data = {
            auditStatus: this.auditForm.auditStatus,
            auditRemark: this.auditForm.auditRemark,
            monthlyFee: monthlyFee,
          };

          auditCheckIn(this.auditForm.id, data)
            .then((response) => {
              this.$modal.msgSuccess("审核成功");
              this.auditOpen = false;
              this.getList();
            })
            .catch((error) => {
              // 捕获余额不足异常
              console.error("审核失败:", error);
            });
        }
      });
    },
    // 取消审核按钮
    cancelAudit() {
      this.auditOpen = false;
      this.resetAudit();
    },
    /** 退住按钮操作 */
    handleCheckOut(row) {
      const id = row.id;
      this.$modal
        .confirm("是否确认办理退住？退住后将清空老人余额。")
        .then(() => {
          return checkOut(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("退住办理成功");
        })
        .catch(() => {});
    },
  },
};
</script>
